/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelIncrementales.java
 *
 * Created on 11-oct-2010, 14:12:47
 */
package interfaz.FuncionPanels.ecuaciones;

import funcion.ManejadorFuncion;
import interfaz.NuMethodApp;
import interfaz.NuMethodConstants;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.table.DefaultTableModel;
import metodos.BusquedasIncrementales;
import metodos.ManejadorMetodo;
import org.jdesktop.swingx.JXHyperlink;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.SearchPredicate;
import org.jdesktop.swingx.decorator.ShadingColorHighlighter;

/**
 *
 * @author The NuMethod Team
 */
public class PanelIncrementales extends javax.swing.JPanel {

    private String f; //El String que representara la funcion f(X) a ejecutar
    /** Arreglo de cabeceras de la tabla Incrementales
     */
    String[] names = {"N", "Xi", "Fxi"};
    private static ImageIcon errorIcon;
    private static ImageIcon okIcon;
    private static ImageIcon halfSuccessIcon;

    /** Creates new form PanelIncrementales */
    public PanelIncrementales() {


        initComponents();
        initComponents2();


    }

    /**
     * Metodo de utilidad para terminar manualmente la inicializacion de la Interfaz
     */
    private void initComponents2() {
        errorIcon = new ImageIcon(getClass().getResource("/recursos/Icons16/agt_action_fail.png"));
        okIcon = new ImageIcon(getClass().getResource("/recursos/Icons16/agt_action_success.png"));
        halfSuccessIcon = new ImageIcon(getClass().getResource("/recursos/Icons16/admin_icon.png"));

        Object[][] data = new Double[2][3];
        DefaultTableModel tm = new DefaultTableModel(data, names);
        TableIncrementales.setModel(tm);
        ShadingColorHighlighter h = new ShadingColorHighlighter();
        h.setHighlightPredicate(new HighlightPredicate.DepthHighlightPredicate(tm.getRowCount()));
        TableIncrementales.setHighlighters(h);

        updateFunctions();
    }

    public void updateFunctions() {
        f = NuMethodApp.getF();
        LabelFText.setText(f);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        SPanelProceso = new javax.swing.JScrollPane();
        TableIncrementales = new org.jdesktop.swingx.JXTable();
        PanelEntrada = new javax.swing.JPanel();
        BotonEjecutar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        FieldInicial = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        FieldDelta = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        FieldIteraciones = new javax.swing.JTextField();
        LabelInStatus = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        PanelSalida = new javax.swing.JPanel();
        LabelSalida = new javax.swing.JLabel();
        LabelSalida2 = new javax.swing.JLabel();
        PanelEstado = new javax.swing.JPanel();
        LabelF = new javax.swing.JLabel();
        LabelFText = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setForeground(new java.awt.Color(255, 0, 255));

        SPanelProceso.setBorder(javax.swing.BorderFactory.createTitledBorder("Proceso"));
        SPanelProceso.setToolTipText("Proceso de salida");

        TableIncrementales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        SPanelProceso.setViewportView(TableIncrementales);

        PanelEntrada.setBorder(javax.swing.BorderFactory.createTitledBorder("Entrada"));

        BotonEjecutar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Icons16/player_play.png"))); // NOI18N
        BotonEjecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonEjecutarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Icons16/1uparrow.png"))); // NOI18N
        jLabel2.setText("Valor Inicial");

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Icons16/1downarrow.png"))); // NOI18N
        jLabel3.setText("Delta");

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Icons16/kodo.png"))); // NOI18N
        jLabel5.setText("Iteraciones");

        FieldIteraciones.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FieldIteracionesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(FieldIteraciones, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(FieldDelta)
                    .addComponent(FieldInicial, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addContainerGap(67, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FieldInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FieldDelta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FieldIteraciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout PanelEntradaLayout = new javax.swing.GroupLayout(PanelEntrada);
        PanelEntrada.setLayout(PanelEntradaLayout);
        PanelEntradaLayout.setHorizontalGroup(
            PanelEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelEntradaLayout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PanelEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(LabelInStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                    .addComponent(BotonEjecutar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        PanelEntradaLayout.setVerticalGroup(
            PanelEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelEntradaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PanelEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(PanelEntradaLayout.createSequentialGroup()
                        .addComponent(LabelInStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(BotonEjecutar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        jLabel1.setText("Metodo de Busquedas Incrementales");

        PanelSalida.setBorder(javax.swing.BorderFactory.createTitledBorder("Salida"));

        javax.swing.GroupLayout PanelSalidaLayout = new javax.swing.GroupLayout(PanelSalida);
        PanelSalida.setLayout(PanelSalidaLayout);
        PanelSalidaLayout.setHorizontalGroup(
            PanelSalidaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelSalidaLayout.createSequentialGroup()
                .addGroup(PanelSalidaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(LabelSalida)
                    .addGroup(PanelSalidaLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(LabelSalida2)))
                .addContainerGap(603, Short.MAX_VALUE))
        );
        PanelSalidaLayout.setVerticalGroup(
            PanelSalidaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelSalidaLayout.createSequentialGroup()
                .addComponent(LabelSalida)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(LabelSalida2)
                .addContainerGap())
        );

        PanelEstado.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        LabelF.setText("f(x) = ");

        javax.swing.GroupLayout PanelEstadoLayout = new javax.swing.GroupLayout(PanelEstado);
        PanelEstado.setLayout(PanelEstadoLayout);
        PanelEstadoLayout.setHorizontalGroup(
            PanelEstadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelEstadoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LabelF)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LabelFText)
                .addContainerGap(528, Short.MAX_VALUE))
        );
        PanelEstadoLayout.setVerticalGroup(
            PanelEstadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelEstadoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PanelEstadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LabelF)
                    .addComponent(LabelFText))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/help.png"))); // NOI18N
        jButton1.setToolTipText("Ayuda");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PanelEntrada, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(10, 10, 10)
                                .addComponent(PanelEstado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(SPanelProceso, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(PanelSalida, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(21, 21, 21))
                    .addComponent(PanelEstado, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PanelEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(SPanelProceso, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(PanelSalida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void FieldIteracionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FieldIteracionesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_FieldIteracionesActionPerformed

    private void reBuildIncrementalesTableModel(
            ArrayList<Integer> Iters,
            ArrayList<Double> Xi,
            ArrayList<Double> Fxi) {
        int n = Xi.size();
        Double[][] data = new Double[n][3];
        for (int i = 0; i < n; i++) {
            data[i][0] = Iters.get(i).doubleValue();
            data[i][1] = Xi.get(i);
            data[i][2] = Fxi.get(i);
        }

        DefaultTableModel tm = new DefaultTableModel(data, names);
        TableIncrementales.setModel(tm);
        tm.fireTableDataChanged();
    }

    private void BotonEjecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonEjecutarActionPerformed
        int Iter = 0;
        double Inicial = 0;
        double Delta = 0;

        int resultStatus = 0;
        if (FieldInicial.getText() != null) {
            if (FieldDelta.getText() != null) {
                if (FieldIteraciones.getText() != null) {
                    // <editor-fold defaultstate="collapsed" desc="Parsear los datos desde la interfaz">
                    ///--------
                    try {
                        Inicial = Double.parseDouble(FieldInicial.getText());
                    } catch (NumberFormatException e) {
                        LabelInStatus.setText("Imposible obtener el numero en el campo Xinferior");
                        return;
                    }
                    ///--------
                    try {
                        Delta = Double.parseDouble(FieldDelta.getText());
                    } catch (NumberFormatException e) {
                        LabelInStatus.setText("Imposible obtener el numero en el campo Xsuperior");
                        return;
                    }
                    ///--------
                    try {
                        Iter = Integer.parseInt(FieldIteraciones.getText());
                    } catch (NumberFormatException e) {
                        LabelInStatus.setText("Imposible parsear el numero en el campo Iteraciones");
                        return; //Orden de salida externa
                    }// </editor-fold>
                    // <editor-fold defaultstate="collapsed" desc="Operar con los datos">
                    //Obtenidos y parseados todos los valores, a trabajar
                    ManejadorFuncion.getInstance().addFuncion("f", "x", f);
                    BusquedasIncrementales.solucionar(Inicial, Delta, Iter);
                    reBuildIncrementalesTableModel(
                            BusquedasIncrementales.Iters,
                            BusquedasIncrementales.Xi,
                            BusquedasIncrementales.Fxi);// </editor-fold>
                    // <editor-fold defaultstate="collapsed" desc="Mostrar el Resultado">
                    //Se termino el metodo, debemos verificar los resultados. e imprimir
                    resultStatus = BusquedasIncrementales.getLatestStatus();
                    Double temp = BusquedasIncrementales.Xi.get(BusquedasIncrementales.Xi.size() - 1);
                    switch (resultStatus) {
                        case (NuMethodConstants.IS_ROOT): {
                            LabelSalida.setText("se hallo una raiz en: " + String.valueOf(temp));
                            LabelSalida.setForeground(Color.GREEN);
                            LabelSalida.setIcon(okIcon);
                            break;
                        }
                        case (NuMethodConstants.IS_ROOT_BETWEEN): {
                            LabelSalida.setText("Se hallo una raiz entre {" + (String.valueOf(temp - Delta)) + ", " + (String.valueOf(temp)) + "}");
                            LabelSalida.setForeground(Color.ORANGE);
                            LabelSalida.setIcon(halfSuccessIcon);
                            break;
                        }
                        case (NuMethodConstants.IS_ERROR): {
                            LabelSalida.setText("No fue posible encontrar un resultado con las iteraciones pedidas. devolviendo los ultimos status");
                            LabelSalida.setForeground(Color.red);
                            LabelSalida.setIcon(errorIcon);
                            LabelSalida2.setText(
                                    "Ultimo valor obtenido: {" + String.valueOf(temp - Delta) + "," + String.valueOf(temp) + "}");
                            break;
                        }
                    }// </editor-fold>

                    //Se obtuvieron los datos, ahora podemos vaciar los arreglos temporales
                    BusquedasIncrementales.flushTempArrays();

                } else {
                    LabelInStatus.setText("Por favor colocar un # de iteraciones");
                }
            } else {
                LabelInStatus.setText("Por favor colocar un Delta");
            }
        } else {
            LabelInStatus.setText("Por favor colocar Valor Inicial");
        }
    }//GEN-LAST:event_BotonEjecutarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        NuMethodApp.helpLauncher("BusquedasIncrementales");
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotonEjecutar;
    private javax.swing.JTextField FieldDelta;
    private javax.swing.JTextField FieldInicial;
    private javax.swing.JTextField FieldIteraciones;
    private javax.swing.JLabel LabelF;
    private javax.swing.JLabel LabelFText;
    private javax.swing.JLabel LabelInStatus;
    private javax.swing.JLabel LabelSalida;
    private javax.swing.JLabel LabelSalida2;
    private javax.swing.JPanel PanelEntrada;
    private javax.swing.JPanel PanelEstado;
    private javax.swing.JPanel PanelSalida;
    private javax.swing.JScrollPane SPanelProceso;
    public org.jdesktop.swingx.JXTable TableIncrementales;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
}
